package cn.qn.common.filter;

import cn.qn.common.configs.IgnorePathConfig;
import cn.qn.common.util.JwtUtil;
import cn.qn.dto.ResponseDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt 过滤器
 * Created by nishu on 2018/4/17.
 */
public class JwtFilter implements Filter {

    private static final Logger LOGGER= LoggerFactory.getLogger(JwtFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final String authHeader = request.getHeader("authorization");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            if(IgnorePathConfig.ignoreRequest(request)){
                filterChain.doFilter(servletRequest, servletResponse);
            }else
            //验证用户是否存在token
            if (authHeader != null && null!=JwtUtil.getUserId(authHeader)) {
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                ObjectMapper mapper = new ObjectMapper();
                response.getWriter().write(mapper.writeValueAsString( ResponseDTO.error("非法的访问")));
            }
        }
    }

    @Override
    public void destroy() {

    }
}
